#!/bin/bash

# Funi原型系统服务器启动脚本 (Mac/Linux版本)
# 版本: 2.0
# 作者: Funi Team

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 图标定义
ROCKET="🚀"
CHECK="✅"
CROSS="❌"
WARNING="⚠️"
INFO="💡"
FOLDER="📁"
GLOBE="🌐"
STOP="🛑"
WAVE="👋"

# 打印带颜色的消息
print_message() {
    local color=$1
    local icon=$2
    local message=$3
    echo -e "${color}${icon} ${message}${NC}"
}

# 打印横幅
print_banner() {
    local port=$1
    local directory=$2
    local url="http://localhost:${port}"
    
    echo
    echo "=================================================================="
    print_message $CYAN $ROCKET "Funi原型系统服务器启动成功!"
    echo "=================================================================="
    print_message $BLUE "📍" "服务器地址: ${url}"
    print_message $BLUE $FOLDER "服务目录: ${directory}"
    print_message $BLUE "🕒" "启动时间: $(date '+%Y-%m-%d %H:%M:%S')"
    echo "=================================================================="
    print_message $YELLOW $INFO "使用提示:"
    echo "  - 服务器启动后会自动打开浏览器"
    echo "  - 修改文件后刷新浏览器即可看到更新"
    echo "  - 按 Ctrl+C 停止服务器"
    echo "  - 现在所有功能都能正常使用!"
    echo "=================================================================="
}

# 检查端口是否可用
check_port() {
    local port=$1
    if command -v nc >/dev/null 2>&1; then
        ! nc -z localhost $port >/dev/null 2>&1
    elif command -v netstat >/dev/null 2>&1; then
        ! netstat -ln | grep ":$port " >/dev/null 2>&1
    else
        # 如果没有nc或netstat，假设端口可用
        return 0
    fi
}

# 查找可用端口
find_available_port() {
    local preferred_port=${1:-8080}
    local ports=(8080 8081 8082 8083 3000 3001 5000 5001 9000 9001)
    
    # 首先尝试首选端口
    if check_port $preferred_port; then
        echo $preferred_port
        return
    fi
    
    # 尝试备选端口
    for port in "${ports[@]}"; do
        if [[ $port != $preferred_port ]] && check_port $port; then
            echo $port
            return
        fi
    done
    
    # 如果都不可用，返回一个随机端口
    echo $((8000 + RANDOM % 1000))
}

# 检查Python环境
check_python() {
    if command -v python3 >/dev/null 2>&1; then
        echo "python3"
    elif command -v python >/dev/null 2>&1; then
        # 检查是否是Python 3
        if python -c "import sys; exit(0 if sys.version_info[0] >= 3 else 1)" 2>/dev/null; then
            echo "python"
        else
            return 1
        fi
    else
        return 1
    fi
}

# 打开浏览器
open_browser() {
    local url=$1
    sleep 1.5  # 等待服务器完全启动
    
    if command -v open >/dev/null 2>&1; then
        # macOS
        open "$url" >/dev/null 2>&1
    elif command -v xdg-open >/dev/null 2>&1; then
        # Linux
        xdg-open "$url" >/dev/null 2>&1
    elif command -v firefox >/dev/null 2>&1; then
        firefox "$url" >/dev/null 2>&1 &
    elif command -v google-chrome >/dev/null 2>&1; then
        google-chrome "$url" >/dev/null 2>&1 &
    elif command -v chromium-browser >/dev/null 2>&1; then
        chromium-browser "$url" >/dev/null 2>&1 &
    else
        print_message $YELLOW $WARNING "无法自动打开浏览器，请手动访问: $url"
        return 1
    fi
    
    print_message $GREEN $GLOBE "浏览器已自动打开: $url"
}

# 信号处理
cleanup() {
    echo
    echo
    print_message $RED $STOP "收到停止信号，正在关闭服务器..."
    print_message $GREEN $WAVE "感谢使用 Funi原型系统!"
    exit 0
}

# 主函数
main() {
    # 设置信号处理
    trap cleanup SIGINT SIGTERM
    
    # 获取脚本的实际路径
    SCRIPT_PATH="$(realpath "$0")"
    SCRIPT_DIR="$(dirname "$SCRIPT_PATH")"
    
    # 切换到script同级的项目根目录（查找index.html）
    PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
    cd "$PROJECT_ROOT"

    # 检查必要文件
    if [[ ! -f "index.html" ]]; then
        print_message $RED $CROSS "未找到 index.html 文件"
        print_message $YELLOW $INFO "请确保项目结构正确，index.html应在项目根目录"
        print_message $YELLOW $INFO "当前目录: $(pwd)"
        print_message $YELLOW $INFO "脚本目录: $SCRIPT_DIR"
        print_message $YELLOW $INFO "项目根目录: $PROJECT_ROOT"
        exit 1
    fi
    
    print_message $GREEN $CHECK "文件检查通过"
    echo
    
    # 检查Python环境
    print_message $BLUE "🔍" "检查Python环境..."
    PYTHON_CMD=$(check_python)
    if [[ $? -ne 0 ]]; then
        print_message $RED $CROSS "未找到Python 3环境"
        echo
        print_message $YELLOW $INFO "请安装Python 3后重试:"
        echo "  - macOS: brew install python3"
        echo "  - Ubuntu/Debian: sudo apt install python3"
        echo "  - CentOS/RHEL: sudo yum install python3"
        echo "  - 或访问: https://www.python.org/downloads/"
        exit 1
    fi
    
    print_message $GREEN $CHECK "找到Python: $($PYTHON_CMD --version)"
    echo
    
    # 解析命令行参数
    preferred_port=${1:-8080}
    
    # 查找可用端口
    port=$(find_available_port $preferred_port)
    if [[ $port != $preferred_port ]]; then
        print_message $YELLOW $WARNING "端口 $preferred_port 不可用，使用端口 $port"
    fi
    
    # 打印启动信息
    print_banner $port "$(pwd)"
    
    # 在后台打开浏览器
    url="http://localhost:$port"
    open_browser "$url" &
    
    echo
    print_message $BLUE "⏳" "服务器运行中... (按 Ctrl+C 停止)"
    echo
    
    # 启动服务器
    if [[ -f "script/start-server.py" ]]; then
        $PYTHON_CMD script/start-server.py $port
    else
        # 备用方案：使用内置HTTP服务器
        $PYTHON_CMD -m http.server $port
    fi
}

# 运行主函数
main "$@"
